package com.ncu.cloundeoffice.service.impl;

import com.ncu.cloundeoffice.config.jwt.JwtTokenUtil;
import com.ncu.cloundeoffice.config.security.SecurityConfig;
import com.ncu.cloundeoffice.mapper.TAdminMapper;
import com.ncu.cloundeoffice.mapper.TAdminRoleMapper;
import com.ncu.cloundeoffice.pojo.Login;
import com.ncu.cloundeoffice.pojo.ResponseResult;
import com.ncu.cloundeoffice.pojo.TAdmin;
import com.ncu.cloundeoffice.pojo.TRole;
import com.ncu.cloundeoffice.service.TAdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpRequest;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class TAdminServiceImpl implements TAdminService {



    @Autowired
    private TAdminMapper tAdminMapper;
    @Autowired
    private TAdminRoleMapper tAdminRoleMapper;
    @Autowired
    private UserDetailsService userDetailsService;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Value("${jwt.tokenHead}")
    private String tokenHead;

    /**
     * 登录
     * @param username
     * @param password
     * @param request
     * @return
     */
    @Override
    public ResponseResult login(String username, String password, HttpServletRequest request) {
        //登录
        UserDetails userDetails = userDetailsService.loadUserByUsername(username);
        if(userDetails == null || !passwordEncoder.matches(password,userDetails.getPassword())){
            return ResponseResult.error("用户名或密码不正确");
        }
        if(!userDetails.isEnabled()){
            return ResponseResult.error("账号被禁用，请联系管理员!");
        }

        //存入SecurityContextHolder
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new
                UsernamePasswordAuthenticationToken(userDetails, null, null);
        SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
        //生成token
        String token = jwtTokenUtil.generateToken(userDetails);
        Map<String,Object> map = new HashMap<>();
        map.put("token",token);
        map.put("tokenHead",tokenHead);
        return ResponseResult.success("登录成功",map);
    }

    /**
     * 通过用户名查出用户信息
     * @param username
     * @return
     */
    @Override
    public TAdmin getAdminByUsername(String username) {
        TAdmin tAdmin = tAdminMapper.getTAdminByUsername(username);
        return tAdmin;
    }

    /**
     * 获取所有操作员
     * @param keyword
     * @return
     */
    @Override
    public List<TAdmin> getAllTAdmins(String keyword) {
        int adminId = ((TAdmin) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getId();
        return tAdminMapper.getAllTAdmins(adminId,keyword);
    }

    /**
     * 修改操作员
     * @param tAdmin
     * @return
     */
    @Override
    public ResponseResult updateTAdmin(TAdmin tAdmin) {
        int count = tAdminMapper.updateTAdmin(tAdmin);
        if(count == 1){
            return ResponseResult.success("更新成功");
        }
        return ResponseResult.error("更新失败") ;
    }

    /**
     * 删除操作员
     * @param id
     * @return
     */
    @Override
    public ResponseResult deleteTAdmin(int id) {
        int count = tAdminMapper.deleteTAdmin(id);
        if(count == 1){
            return ResponseResult.success("删除成功");
        }
        return ResponseResult.error("删除失败");
    }

    /**
     * 获取所有的角色
     * @return
     */
    @Override
    public List<TRole> getAllRoles() {
        return tAdminRoleMapper.getAllRoles();
    }

    /**
     * 更新操作员角色
     * @param adminId
     * @param rids
     * @return
     */
    @Override
    @Transactional
    public ResponseResult updateTAdminRole(int adminId, int[] rids) {
        tAdminRoleMapper.deleteAllRoleByTAdmin(adminId);
        if(rids.length == 0 || rids == null){
            return ResponseResult.success("更新成功");
        }
        int count = tAdminRoleMapper.insertTAdminRole(adminId,rids);
        if(count == rids.length){
            return ResponseResult.success("更新成功");
        }
        return ResponseResult.error("更新失败");

    }

    /**
     * 修改用户信息
     * @param tAdmin
     * @return
     */
    @Override
    public int updateTAdminInfo(TAdmin tAdmin) {
        return  tAdminMapper.updateTAdminInfo(tAdmin);

    }

    /**
     * 修改密码
     * @param oldPassword
     * @param pass
     * @param adminId
     * @return
     */
    @Override
    public ResponseResult updatePass(String oldPassword, String pass, Integer adminId) {
        TAdmin tAdmin = tAdminMapper.selectById(adminId);
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        if(encoder.matches(oldPassword,tAdmin.getPassword())){
            tAdmin.setPassword(encoder.encode(pass));
            int count = tAdminMapper.updatePassword(tAdmin);
            if(count == 1){
                return  ResponseResult.success("修改成功");
            }
        }
        return ResponseResult.error("修改失败");
    }

    /**
     * 修改头像
     * @param adminId
     * @param storeAddress
     * @return
     */
    @Override
    public int updateUserFace(int adminId, String storeAddress) {
        return tAdminMapper.updateUserFace(adminId,storeAddress);
    }
}
